package com.zgc.zkinfo;

import com.zgc.cache.CuratorClientCache;
import com.zgc.listener.CuratorTreeCacheListener;
import org.apache.curator.framework.recipes.cache.CuratorCache;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CuratorCacheFactory {

    private static final Map<String, Map<String, CuratorCache>> CURATOR_CACHE_MAP = new ConcurrentHashMap<>();


    public static CuratorCache createTreeCacheListener(ZkConnectionInfo connectClient, String path) {
        CuratorCache curatorCache = CuratorCache.build(CuratorClientCache.getCuratorClient(connectClient.getId()), path);
        curatorCache.listenable().addListener(new CuratorTreeCacheListener(connectClient));
        CURATOR_CACHE_MAP.computeIfAbsent(connectClient.getId(), key -> new ConcurrentHashMap<>()).put(path, curatorCache);
        return curatorCache;
    }

    public static CuratorCache getTreeCacheListener(String id, String path) {
        return CURATOR_CACHE_MAP.get(id).get(path);
    }


    public static void close(String id, String path) {
        getTreeCacheListener(id, path).close();
    }

    public static void close(String id) {
        CURATOR_CACHE_MAP.get(id).forEach((key, value) -> value.close());
    }
}
